package com.xjysx.xiaochetong.moudle;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.serialport.SerialPortConstants;
import android.serialport.SerialPortEvent;
import android.serialport.SerialPortUtil;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.serialportlibrary.util.LogUtil;
import com.xjysx.xiaochetong.R;
import com.xjysx.xiaochetong.base.BaseActivity;
import com.xjysx.xiaochetong.entities.EndCountDownEvent;
import com.xjysx.xiaochetong.network.BaseBean;
import com.xjysx.xiaochetong.network.BaseObserver;
import com.xjysx.xiaochetong.network.Network;
import com.xjysx.xiaochetong.util.PollingUtil;
import com.xjysx.xiaochetong.util.SignatureUtil;
import com.xjysx.xiaochetong.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xjysx.xiaochetong.network.Network.END;
import static com.xjysx.xiaochetong.network.Network.GET_TIME_PAY;
import static com.xjysx.xiaochetong.network.Network.GET_TIME_USE;
import static com.xjysx.xiaochetong.network.Network.START;


public class MainActivity extends BaseActivity {


    @BindView(R.id.iv_bg)
    ImageView iv_bg;
    @BindView(R.id.view_back)
    View viewBack;
    @BindView(R.id.view_start)
    View viewStart;
    @BindView(R.id.cet_big)
    View cetBig;
    @BindView(R.id.cet_middle)
    View cetMiddle;
    @BindView(R.id.cet_small)
    View cetSmall;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_mode)
    TextView tvMode;
    @BindView(R.id.time_dec)
    View timeDec;
    @BindView(R.id.time_add)
    View timeAdd;
    @BindView(R.id.view_time_ll)
    LinearLayout viewTimeLl;
    @BindView(R.id.mode_dec)
    View modeDec;
    @BindView(R.id.mode_add)
    View modeAdd;
    @BindView(R.id.view_mode_ll)
    LinearLayout viewModeLl;
    @BindView(R.id.view_energy_dec)
    View viewEnergyDec;
    @BindView(R.id.view_energy_add)
    View viewEnergyAdd;
    @BindView(R.id.tv_energy)
    TextView tvEnergy;
    @BindView(R.id.tv_hour)
    TextView tvHour;
    @BindView(R.id.tv_minute)
    TextView tvMinute;
    @BindView(R.id.tv_second)
    TextView tvSecond;
    @BindView(R.id.tv_test)
    TextView tvTest;
    @BindView(R.id.ll_size)
    LinearLayout llSize;
    @BindView(R.id.tv_time_tie)
    TextView tvTimeTie;
    @BindView(R.id.tv_mode_tie)
    TextView tvModeTie;
    @BindView(R.id.tie_mode_dec)
    View viewModeDec;
    @BindView(R.id.tie_mode_add)
    View viewModeAdd;
    @BindView(R.id.ll_mode_tie)
    LinearLayout llModeTie;

    private AlertDialog.Builder builder;


    int type = 1;
    //1 大  2中  3小
    int cet_size = 1;
    //1 大  2中
    int ret_size = 1;

    boolean ret_start = false;
    boolean cet_start = false;
    boolean chao_start = false;
    boolean tie_start = false;

    int function_time = 1800;
    int time = 0;
    int mode = 1;
    int energy = 0;
    int energy1 = 0;
    String status = "0";

    boolean timeStarted = false;
    boolean time2Started = false;
    boolean time3Started = false;


    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            LogUtil.e(time + "");
            time--;
            EventBus.getDefault().post(new EndCountDownEvent(1));
            preferences.edit().putInt("time", time).apply();
        }
    };

    Timer timer2 = new Timer();
    TimerTask task2 = new TimerTask() {
        @Override
        public void run() {
            LogUtil.e(time + "");
            if (function_time > 0) {
                function_time--;
            }
            EventBus.getDefault().post(new EndCountDownEvent(2));
        }
    };

    Timer timer3 = new Timer();
    TimerTask task3 = new TimerTask() {
        @Override
        public void run() {
            EventBus.getDefault().post(new UpdateTimeEvent());
        }
    };


    private BaseObserver<Object> observer_pay_time = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
            if (bean == null) {
//                ToastUtil.showToast(BaseApplication.getInstance(), "time_use接口返回：null");
                return;
            }
//            ToastUtil.showToast(BaseApplication.getInstance(), "time_use接口返回：" + bean.toString());
            if (((Map) bean).containsKey("time_pay")) {
                double time_pay = (double) ((Map) bean).get("time_pay");
                if (time_pay > 0) {
                    time = Double.valueOf(time_pay).intValue();//单位为秒
                    setPayTimeText();
                    preferences.edit().putInt("time", time).apply();

                }
                if (preferences.getBoolean("started", false)) {
                    if (timer != null) {
                        timer.schedule(task, 0, 1000);
                    } else {
                        task = new TimerTask() {
                            @Override
                            public void run() {
                                LogUtil.e(time + "");
                                if (time > 0) {
                                    time--;
                                }
                                EventBus.getDefault().post(new EndCountDownEvent(1));
                            }
                        };
                        timer.schedule(task, 0, 1000);
                        timeStarted = true;
                    }
                }
            }
            if (((Map) bean).containsKey("time_use")) {
                double time_pay = (double) ((Map) bean).get("time_use");
                if (time_pay > 0) {
                    time = Double.valueOf(time_pay).intValue();//单位为秒
                    preferences.edit().putInt("time", time).apply();
                    setPayTimeText();
                    if (time > 300) {
                        timer3.cancel();
                        timer3 = null;
                        task3 = null;
                        timer3 = new Timer();
                        task3 = new TimerTask() {
                            @Override
                            public void run() {
                                EventBus.getDefault().post(new UpdateTimeEvent());
                            }
                        };
                    }
                }
            }
        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };

    private BaseObserver<Object> observer_start = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
            if (bean == null) {
                return;
            }
            if (!preferences.getBoolean("started", false)) {
                if (((Map) bean).containsKey("time_pay")) {
                    double time_pay = (double) ((Map) bean).get("time_pay");
                    if (time_pay > 0) {
                        time = new Double(time_pay).intValue();//单位为秒
                        setPayTimeText();
                    } else {
                        ToastUtil.showToast(getContext(), "该套餐时长剩余0分钟,无法开始");
                        return;
                    }
                }
                if (type == SelectActivity.RET) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_START);
                } else  if (type == SelectActivity.CET) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_START);
                } else  if (type == SelectActivity.CHAO) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_START);
                }else  if (type == SelectActivity.TIE) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_START);
                }
            }
            preferences.edit().putBoolean("started", true).apply();
        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };
    private BaseObserver<Object> observer_time_use = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
            preferences.edit().putBoolean("started", true).apply();

        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };

    private void setPayTimeText() {
        int hour = time / 60 / 60;
        int minute = time / 60 % 60;
        int second = time % 60;
        if (hour == 1 && minute == 0 && second == 0) {
            tvHour.setText("00");
            tvMinute.setText("60");
            tvSecond.setText("00");
        } else {
            tvHour.setText(hour < 10 ? "0" + hour : hour + "");
            tvMinute.setText(minute < 10 ? "0" + minute : minute + "");
            tvSecond.setText(second < 10 ? "0" + second : second + "");
        }

    }

    private BaseObserver<Object> observer_end = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };


    private String TAG = "MainActivity";
    private MainActivity mainActivity;
    private PollingUtil pollingUtil;
    private Runnable runnable;

    @Override
    protected void loadLayout() {
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        super.initialize(savedInstanceState);
        type = getIntent().getIntExtra("type", 1);
        if (type == SelectActivity.CET) {
            iv_bg.setImageResource(R.drawable.cet_big);
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_CET);
        } else if (type == SelectActivity.CHAO) {
            iv_bg.setImageResource(R.drawable.chao);
            llSize.setVisibility(View.GONE);
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_CHAO);
        } else if (type == SelectActivity.TIE) {
            iv_bg.setImageResource(R.drawable.tie);
            llSize.setVisibility(View.GONE);
            llModeTie.setVisibility(View.VISIBLE);
            tvModeTie.setVisibility(View.VISIBLE);
            tvTimeTie.setVisibility(View.VISIBLE);
            tvEnergy.setVisibility(View.GONE);
            tvTime.setText("0");
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_TIE);
        } else {
            iv_bg.setImageResource(R.drawable.ret_big);
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_RET);
        }
    }


    @Override
    public void initPresenter() {
        mainActivity = this;
        EventBus.getDefault().register(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        super.processLogic(savedInstanceState);
        if (preferences.getBoolean("started", false)) {
            time = preferences.getInt("time", 0);
            setPayTimeText();
            timer.schedule(task, 0, 1000);
            if (time <= 300) {
                timer3.schedule(task3, 0, 60000);
            }
        } else {
            getPayTime();
        }
    }

    private void showDialog(String content) {
        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        builder.create().show();
    }


    private void showEndDialog(String content) {
        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                            task = null;
                            timeStarted = false;
                        }
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                            time2Started = false;
                        }
                        finish();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void getPayTime() {
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(GET_TIME_PAY, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer_pay_time);
    }

    private void getTimeUse() {
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(GET_TIME_USE, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer_pay_time);
    }

    private void start() {
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(START, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer_start);
    }

    private void end(String status) {
        this.status = status;
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String function = "";
        if (type == SelectActivity.RET) {
            if (ret_size == 1) {
                function = "ret_big";
            } else if (ret_size == 2) {
                function = "ret_center";
            }
        } else {
            if (cet_size == 1) {
                function = "cet_big";
            } else if (cet_size == 2) {
                function = "cet_center";
            } else if (cet_size == 3) {
                function = "cet_small";
            }
        }
        map.put("function", function);
        map.put("moshi", mode + "");
        map.put("nengliang", energy + "");
        map.put("time", function_time + "");
        map.put("status", status);

        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(END, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer_end);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateTime(UpdateTimeEvent event) {
        getTimeUse();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void endRolling(EndCountDownEvent endCountDownEvent) {
        if (endCountDownEvent.type == 1) {
            if (time >= 0) {
                setPayTimeText();
            }
            if (time == 5 * 60) {//提示
                showDialog("该套餐时长仅剩5分钟,如需修改,请联系管理员");
                timer3.schedule(task3, 0, 60000);
            }
            if (time <= 0) {
                end("1");
                if (time == -5) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                        task = null;
                        timeStarted = false;
                    }
                    if (timer2 != null) {
                        timer2.cancel();
                        timer2 = null;
                        task2 = null;
                        time2Started = false;
                    }
                    finish();
                }
                showEndDialog("套餐时间结束，请重新扫码");
                if (type == SelectActivity.RET) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_RESET);
                } else  if (type == SelectActivity.CET){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_RESET);
                }else  if (type == SelectActivity.CHAO){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_RESET);
                }else  if (type == SelectActivity.TIE){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_RESET);
                }
                preferences.edit().putBoolean("started", false).apply();
                return;
            }
        } else if (endCountDownEvent.type == 2) {
            setTimeText();
            if (function_time <= 0) {
                if (type == SelectActivity.RET) {
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_RESET);
                } else  if (type == SelectActivity.CET){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_RESET);
                }else  if (type == SelectActivity.CHAO){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_RESET);
                }else  if (type == SelectActivity.TIE){
                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_END);
//                    SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_RESET);
                }
                if (timer2 != null) {
                    timer2.cancel();
                    timer2 = null;
                    task2 = null;
                    time2Started = false;
                }
                end("0");
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveData(SerialPortEvent event) {
        byte[] data = event.data;
        int cmd = event.cmd;
        if (cmd == 2) {
            return;
        }
        tvTest.setText(String.format("接收到指令：%s  数据：%s ", cmd, SerialPortConstants.byteArrayToHex(event.data)));
        byte[] body = null;
        String content = "";
        //根据功能处理界面
        switch (cmd) {
            case 3://恢复初始化状态
            case 6://恢复初始化状态
            case 15://恢复初始化状态
            case 28://恢复初始化状态
            case 35://恢复初始化状态
                //body  参数位+数据
                body = new byte[data.length - 6];
                for (int i = 0; i < data.length - 6; i++) {
                    body[i] = data[i + 5];
                }
                content = SerialPortConstants.byteArrayToString(body);
                if (content.equals("OK")) {//
                    if (type == SelectActivity.CET) {
                        cet_start = false;
                        if(cet_size ==1) {
                            iv_bg.setImageResource(R.drawable.cet_big);
                        }else if(cet_size ==2){
                            iv_bg.setImageResource(R.drawable.cet_middle);
                        }else if(cet_size ==3){
                            iv_bg.setImageResource(R.drawable.cet_small);
                        }
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_CET);
                    } else if (type == SelectActivity.CHAO) {
                        chao_start = false;
                        iv_bg.setImageResource(R.drawable.chao);
                        llSize.setVisibility(View.GONE);
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_CHAO);
                    } else if (type == SelectActivity.TIE) {
                        tie_start = false;
                        iv_bg.setImageResource(R.drawable.tie);
                        llSize.setVisibility(View.GONE);
                        llModeTie.setVisibility(View.VISIBLE);
                        tvModeTie.setVisibility(View.VISIBLE);
                        tvTimeTie.setVisibility(View.VISIBLE);
                        tvEnergy.setVisibility(View.GONE);
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_TIE);
                    } else {
                        ret_start = false;
                        if(cet_size ==1) {
                            iv_bg.setImageResource(R.drawable.ret_big);
                        }else if(cet_size ==2){
                            iv_bg.setImageResource(R.drawable.ret_middle);
                        }else if(cet_size ==3){
                            iv_bg.setImageResource(R.drawable.ret_small);
                        }
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.SELECT_RET);
                    }
                    function_time = 1800;
                    setTimeText();
                    tvEnergy.setText("0");
                    mode = 1;
                    tvMode.setText("1");
                    if(type == SelectActivity.TIE){
                        tvModeTie.setText("1");
                        tvMode.setText("0");
                        tvTime.setText("0");
                    }
                }
                break;
            case 4://选择RET功能  点击了开始
                body = new byte[data.length - 6];
                for (int i = 0; i < data.length - 6; i++) {
                    body[i] = data[i + 5];
                }
                content = SerialPortConstants.byteArrayToString(body);
                if (content.equals("OK")) {//开始ret
                    ret_start = true;
                    if (ret_size == 1) {
                        iv_bg.setImageResource(R.drawable.ret_big_started);
                    } else if (ret_size == 2) {
                        iv_bg.setImageResource(R.drawable.ret_middle_started);
                    }else if (ret_size == 3) {
                        iv_bg.setImageResource(R.drawable.ret_small_started);
                    }

                }
                break;
            case 5://选择CET功能
                body = new byte[data.length - 6];
                for (int i = 0; i < data.length - 6; i++) {
                    body[i] = data[i + 5];
                }
                content = SerialPortConstants.byteArrayToString(body);
                if (content.equals("OK")) {//开始ret
                    cet_start = true;
                    if (ret_size == 1) {
                        iv_bg.setImageResource(R.drawable.cet_big_started);
                    } else if (ret_size == 2) {
                        iv_bg.setImageResource(R.drawable.cet_middle_started);
                    } else if (ret_size == 3) {
                        iv_bg.setImageResource(R.drawable.cet_small_started);
                    }
                }

                break;
            case 7://选择RET大手柄
            case 8://选择RET大手柄
            case 25://选择RET小手柄
                if (data[4] == 3) {//参数编号  0x01=RET大手柄，0x02=RET中手柄
                    if (data[5] == 1) {//切换手柄
                        ret_size = 1;
                        iv_bg.setImageResource(R.drawable.ret_big);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                    } else if (data[5] == 2) {
                        ret_size = 2;
                        iv_bg.setImageResource(R.drawable.ret_middle);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                    } else if (data[5] == 3) {
                        ret_size = 3;
                        iv_bg.setImageResource(R.drawable.ret_small);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                    }
                }
                break;
            case 9://RET模式减
            case 10://RET模式加
                if (data[4] == 4) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvMode.setText(String.format("%s", data[5]));
                    mode = data[5];
                }
                break;
            case 11://RET能量减
            case 12://RET能量加
                if (data[4] == 5) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvEnergy.setText(String.format("%s", data[5]));
                    energy = data[5];
                }
                break;
            case 13://RET开
            case 14://RET关
                if (data[4] == 6) {//0x00=关闭，0x01=启动
                    if (data[5] == 0) {
                        ret_start = false;
                        if (ret_size == 1) {
                            iv_bg.setImageResource(R.drawable.ret_big);
                        } else if (ret_size == 2) {
                            iv_bg.setImageResource(R.drawable.ret_middle);
                        } else if (ret_size == 3) {
                            iv_bg.setImageResource(R.drawable.ret_small);
                        }
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                            time2Started = false;
                        }
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                    } else {
                        ret_start = true;
                        if (ret_size == 1) {
                            iv_bg.setImageResource(R.drawable.ret_big_started);
                        } else if (ret_size == 2) {
                            iv_bg.setImageResource(R.drawable.ret_middle_started);
                        } else if (ret_size == 3) {
                            iv_bg.setImageResource(R.drawable.ret_small_started);
                        }
                        timeStart();
                    }
                }
                break;
            case 16://选择CET大手柄
            case 17://选择CET中手柄
            case 18://选择CET小手柄
                if (data[4] == 7) {
                    if (data[5] == 1) {
                        cet_size = 1;
                        iv_bg.setImageResource(R.drawable.cet_big);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        mode = 1;
                        tvMode.setText("1");
                        tvEnergy.setText("0");
                    } else if (data[5] == 2) {
                        cet_size = 2;
                        iv_bg.setImageResource(R.drawable.cet_middle);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        mode = 1;
                        tvEnergy.setText("0");
                        tvMode.setText("1");
                    } else if (data[5] == 3) {
                        cet_size = 3;
                        iv_bg.setImageResource(R.drawable.cet_small);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        mode = 1;
                        tvMode.setText("1");
                        tvEnergy.setText("0");
                    }
                }
                break;
            case 19://CET模式减
            case 20://CET模式加
                if (data[4] == 8) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvMode.setText(String.format("%s", data[5]));
                    mode = data[5];
                }
                break;
            case 21://CET能量减
            case 22://CET能量加
                if (data[4] == 9) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvEnergy.setText(String.format("%s", data[5]));
                    energy = data[5];
                }
                break;
            case 23://CET开关
            case 24://CET开关
                if (data[4] == 10) {//0x00=关闭，0x01=启动
                    if (data[5] == 0) {
                        cet_start = false;
                        if (cet_size == 1) {
                            iv_bg.setImageResource(R.drawable.cet_big);
                        } else if (cet_size == 2) {
                            iv_bg.setImageResource(R.drawable.cet_middle);
                        } else if (cet_size == 3) {
                            iv_bg.setImageResource(R.drawable.cet_small);
                        }
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                            time2Started = false;
                        }
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                    } else {
                        cet_start = true;
                        if (cet_size == 1) {
                            iv_bg.setImageResource(R.drawable.cet_big_started);
                        } else if (cet_size == 2) {
                            iv_bg.setImageResource(R.drawable.cet_middle_started);
                        } else if (cet_size == 3) {
                            iv_bg.setImageResource(R.drawable.cet_small_started);
                        }
                        timeStart();
                    }
                }
                break;
            case 26://选择超声波功能
                body = new byte[data.length - 6];
                for (int i = 0; i < data.length - 6; i++) {
                    body[i] = data[i + 5];
                }
                content = SerialPortConstants.byteArrayToString(body);
                if (content.equals("OK")) {//开始超声波
                    chao_start = true;
                    iv_bg.setImageResource(R.drawable.chao_started);
                }
                break;
            case 29://超声波模式减
            case 30://超声波模式加
                if (data[4] == 11) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvMode.setText(String.format("%s", data[5]));
                    mode = data[5];
                }
                break;
            case 31://超声波能量减
            case 32://超声波能量加
                if (data[4] == 12) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvEnergy.setText(String.format("%s", data[5]));
                    energy = data[5];
                }
                break;
            case 33://超声波开
            case 34://超声波关
                if (data[4] == 13) {//0x00=关闭，0x01=启动
                    if (data[5] == 0) {
                        chao_start = false;
                        iv_bg.setImageResource(R.drawable.chao);
                        function_time = 1800;
                        tvTime.setText("30：00");
                        tvEnergy.setText("0");
                        mode = 1;
                        tvMode.setText("1");
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                            time2Started = false;
                        }
                    } else {
                        chao_start = true;
                        iv_bg.setImageResource(R.drawable.chao_started);
                        timeStart();
                    }
                }
                break;
            case 36://贴模式减
            case 37://贴模式加
                if (data[4] == 14) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvModeTie.setText(String.format("%s", data[5]));
                    mode = data[5];
                }
                break;
            case 38://A贴减
            case 39://A贴加
                if (data[4] == 15) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvTime.setText(String.format("%s", data[5]));
                    energy = data[5];
                }
                break;
            case 40://B贴减
            case 41://B贴加
                if (data[4] == 16) {//如当前模式参数值大于最小值，参数值减1，否则参数值为最小值，然后应答更改后的参数值，04=参数编号，03=参数值。
                    tvMode.setText(String.format("%s", data[5]));
                    energy1 = data[5];
                }
                break;
            case 42://贴开
            case 43://贴关
                if (data[4] == 17) {//0x00=关闭，0x01=启动
                    if (data[5] == 0) {
                        tie_start = false;
                        iv_bg.setImageResource(R.drawable.tie);
                        function_time = 1800;
                        tvTime.setText("0");
                        mode = 1;
                        tvMode.setText("0");
                        tvModeTie.setText("1");
                        tvTimeTie.setText("30：00");
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                            time2Started = false;
                        }
                    } else {
                        tie_start = true;
                        iv_bg.setImageResource(R.drawable.tie_started);
                        timeStart();
                    }
                }
                break;
            default:
                break;
        }

    }

    private void timeStart() {
        if (timer == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    LogUtil.e(time + "");
                    if (time > 0) {
                        time--;
                    }
                    EventBus.getDefault().post(new EndCountDownEvent(1));
                }
            };
            timer.schedule(task, 0, 1000);
            timeStarted = true;
        } else {
            if (!timeStarted) {
                timeStarted = true;
                try {
                    timer.schedule(task, 0, 1000);
                } catch (Exception e) {

                }
            }
        }
        if (timer2 == null) {
            timer2 = new Timer();
            task2 = new TimerTask() {
                @Override
                public void run() {
                    if (function_time > 0) {
                        function_time--;
                    }
                    EventBus.getDefault().post(new EndCountDownEvent(2));
                }
            };
            timer2.schedule(task2, 0, 1000);
            time2Started = true;
        } else {
            if (!time2Started) {
                timer2.schedule(task2, 0, 1000);
                time2Started = true;
            }
        }
    }


    @OnClick({R.id.view_back, R.id.view_start, R.id.cet_big, R.id.cet_middle,
            R.id.cet_small, R.id.time_dec, R.id.time_add, R.id.mode_dec,
            R.id.mode_add, R.id.view_energy_dec, R.id.view_energy_add,
            R.id.tv_update, R.id.tie_mode_dec, R.id.tie_mode_add})
    public void onViewClicked(View view) {

        byte[] sendByte = null;

        switch (view.getId()) {
            case R.id.tv_update:
                getPayTime();
                return;
            case R.id.view_back:
                if (ret_start || cet_start || chao_start || tie_start) {
                    showDialog("请先暂停再返回");
                    return;
                }
                Intent intent = new Intent(this, SelectActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.view_start:

                if (function_time == 0) {
                    ToastUtil.showToast(this, "请先设置时间");
                    return;
                }

                if (type == SelectActivity.RET) {
                    if (!ret_start) {
                        if (preferences.getBoolean("started", false)) {
                            SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_START);
                        }
                        start();
                    } else {
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_END);
                        end("0");
                    }
                } else if (type == SelectActivity.CHAO) {
                    if (!chao_start) {
                        if (preferences.getBoolean("started", false)) {
                            SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_START);
                        }
                        start();
                    } else {
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_END);
                        end("0");
                    }
                } else if (type == SelectActivity.TIE) {
                    if (!tie_start) {
                        if (preferences.getBoolean("started", false)) {
                            SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_START);
                        }
                        start();
                    } else {
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_END);
                        end("0");
                    }
                } else {
                    if (!cet_start) {
                        if (preferences.getBoolean("started", false)) {
                            SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_START);
                        }
                        start();
                    } else {
                        SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_END);
                        end("0");
                    }
                }

                break;
            case R.id.cet_big:
                if (type == SelectActivity.RET) {
                    if (ret_size == 1) {
                        return;
                    }
                } else {
                    if (cet_size == 1) {
                        return;
                    }
                }

                if (ret_start || cet_start) {
                    showDialog("请先暂停再选择手柄");
                    break;
                }
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_BIG;
                } else {
                    sendByte = SerialPortConstants.CET_BIG;
                }
                break;
            case R.id.cet_middle:
                if (type == SelectActivity.RET) {
                    if (ret_size == 2) {
                        return;
                    }
                } else {
                    if (cet_size == 2) {
                        return;
                    }
                }
                if (ret_start || cet_start) {
                    showDialog("请先暂停再选择手柄");
                    break;
                }
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_MIDDLE;
                } else {
                    sendByte = SerialPortConstants.CET_MIDDLE;
                }
                break;
            case R.id.cet_small:
                if (type == SelectActivity.CET) {
                    if (cet_size == 3) {
                        return;
                    }
                } else {
                    if (ret_size == 3) {
                        return;
                    }
                }
                if (ret_start || cet_start) {
                    showDialog("请先暂停再选择手柄");
                    break;
                }
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_SMALL;
                } else {
                    sendByte = SerialPortConstants.CET_SMALL;
                }
                break;
            case R.id.time_dec:
                if (type != SelectActivity.TIE) {
                    if (function_time >= 60) {
                        function_time -= 60;
                    }
                    setTimeText();
                } else {
                    sendByte = SerialPortConstants.TIE_ENERGY_DEC;
                }
                break;
            case R.id.time_add:
                if (type != SelectActivity.TIE) {
                    function_time += 60;
                    setTimeText();
                } else {
                    sendByte = SerialPortConstants.TIE_ENERGY_ADD;
                }
                break;
            case R.id.mode_dec:
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_MOD_DEC;
                } else if (type == SelectActivity.CHAO) {
                    sendByte = SerialPortConstants.CHAO_MOD_DEC;
                } else if (type == SelectActivity.TIE) {
                    sendByte = SerialPortConstants.TIE_ENERGY_DEC1;
                } else {
                    sendByte = SerialPortConstants.CET_MOD_DEC;
                }
                break;
            case R.id.mode_add:
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_MOD_ADD;
                } else if (type == SelectActivity.CHAO) {
                    sendByte = SerialPortConstants.CHAO_MOD_ADD;
                } else if (type == SelectActivity.TIE) {
                    sendByte = SerialPortConstants.TIE_ENERGY_ADD1;
                } else {
                    sendByte = SerialPortConstants.CET_MOD_ADD;
                }
                break;
            case R.id.view_energy_dec:
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_ENERGY_DEC;
                } else if (type == SelectActivity.CHAO) {
                    sendByte = SerialPortConstants.CHAO_ENERGY_DEC;
                } else if (type == SelectActivity.TIE) {
                    if (function_time >= 60) {
                        function_time -= 60;
                    }
                    setTimeText();
                } else {
                    sendByte = SerialPortConstants.CET_ENERGY_DEC;
                }
                break;
            case R.id.view_energy_add:
                if (type == SelectActivity.RET) {
                    sendByte = SerialPortConstants.RET_ENERGY_ADD;
                } else if (type == SelectActivity.CHAO) {
                    sendByte = SerialPortConstants.CHAO_ENERGY_ADD;
                } else if (type == SelectActivity.TIE) {
                    function_time += 60;
                    setTimeText();
                } else {
                    sendByte = SerialPortConstants.CET_ENERGY_ADD;
                }
                break;
            case R.id.tie_mode_dec:
                sendByte = SerialPortConstants.TIE_MOD_DEC;
                break;
            case R.id.tie_mode_add:
                sendByte = SerialPortConstants.TIE_MOD_ADD;
                break;
            default:
                break;
        }
        if (sendByte != null) {
            LogUtil.e("sendByte:" + SerialPortConstants.byteArrayToHexArray(sendByte));
            ToastUtil.showToast(this, "发送指令：" + SerialPortConstants.byteArrayToHex(sendByte));
            SerialPortUtil.sendSerialPortByte(sendByte);
        }

    }

    private void setTimeText() {
        int minute = function_time / 60;
        int second = function_time % 60;
        String minuteStr = minute < 10 ? "0" + minute : minute + "";
        String secondStr = second < 10 ? "0" + second : second + "";
        if(type != SelectActivity.TIE) {
            tvTime.setText(String.format("%s：%s", minuteStr, secondStr));
        }else{
            tvTimeTie.setText(String.format("%s：%s", minuteStr, secondStr));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
            task = null;
        }
        if (timer2 != null) {
            timer2.cancel();
            timer2 = null;
            task2 = null;
        }
        if (timer3 != null) {
            timer3.cancel();
            timer3 = null;
            task3 = null;
        }
        if (type == SelectActivity.RET) {
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.RET_RESET);
        } else if (type == SelectActivity.CET) {
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.CET_RESET);
        } else if (type == SelectActivity.CHAO) {
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.CHAO_RESET);
        } else if (type == SelectActivity.TIE) {
            SerialPortUtil.sendSerialPortByte(SerialPortConstants.TIE_RESET);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (ret_start || cet_start || chao_start || tie_start) {
            showDialog("请先暂停再返回");
            return;
        }
        Intent intent = new Intent(getContext(), SelectActivity.class);
        startActivity(intent);
        finish();
    }

}
